use actix_web::{get, post, Responder, HttpResponse, HttpRequest};
use crate::base;
use std::ops::Deref;
use crate::server::time_server;
use log::info;
use crate::server::aes_server;
use crate::common::JsonResult;
use std::time::Instant;

pub fn init_time_server() {
    time_server::timekeeping();
}

#[get("/secret")]
pub async fn get_current_base_file(request: HttpRequest) -> impl Responder {
    let instant = Instant::now();
    let conn_info = request.connection_info();
    let address = conn_info.remote_addr().unwrap();
    info!("get/secret <-{}- ", address);
    match serde_json::to_string(base::current_base().deref()) {
        Ok(json) => {
            info!("get/secret -{}ms-{}> `{}`",instant.elapsed().as_millis(),address, json);
            HttpResponse::Ok().content_type("application/json").body(json)
        }
        Err(e) => { HttpResponse::InternalServerError().body(e.to_string()) }
    }
}

#[post("/secret")]
pub async fn import_time(request: HttpRequest, secret: String) -> impl Responder {
    let instant = Instant::now();
    let conn_info = request.connection_info();
    let address = conn_info.remote_addr().unwrap();
    info!("post/secret <-{}- `{}`", address, secret);
    let success = aes_server::import_secret(&secret);
    info!("post/secret -{}ms-{}-> `{:?}`",instant.elapsed().as_millis(),address, success);
    match success {
        Ok(_) => { HttpResponse::Ok().json(JsonResult::success()) }
        Err(e) => { HttpResponse::Ok().json(JsonResult::failed(500, &e.get_message())) }
    }
}